import { Body, Controller, Delete, Get, Header, Param, Patch, Post, Res } from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { Response } from 'express';
import { AichatService } from './aichat.service';
import { CreateAichatDto, sendAichatDto } from './dto/create-aichat.dto';
import { UpdateAichatDto } from './dto/update-aichat.dto';

@Controller('aichat')
@ApiTags('AI')
export class AichatController {
  constructor(private readonly aichatService: AichatService) { }

  @Post()
  create(@Body() createAichatDto: CreateAichatDto) {
    return this.aichatService.create(createAichatDto);
  }

  @ApiOperation({ summary: '发送对话' })
  @Post('/sse')
  @Header('Content-type', 'text/event-stream')
  @Header('Cache-Control', 'no-cache')
  @Header('Connection', 'keep-alive')
  send(@Body() data: sendAichatDto, @Res() res:Response) {
    res.header('Content-type', 'text/event-stream')
    res.flushHeaders()
    this.aichatService.sendMessage(data).subscribe({
      next:(item)=>{
        res.write(`data:${item}`)
        console.log(item)
      },
      error:(err)=>{
        console.error(err)
      },
      complete:()=>{
        res.end()
      }
    })
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.aichatService.findOne(+id);
  }

  @Patch(':id')
  update(@Param('id') id: string, @Body() updateAichatDto: UpdateAichatDto) {
    return this.aichatService.update(+id, updateAichatDto);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.aichatService.remove(+id);
  }
}
